# -*- coding: utf-8 -*-

import datetime
import decimal
import json
import uuid
import frappe
from werkzeug.wrappers import Response
from reportbro import Report, ReportBroError
from timeit import default_timer as timer

MAX_CACHE_SIZE = (
    1000 * 1024 * 1024
)  # keep max. 1000 MB of generated pdf files in sqlite db

@frappe.whitelist()
def run():        
    if frappe.request.method == "OPTIONS":
        # options request is usually sent by browser for a cross-site request, we only need to set the
        # Access-Control-Allow headers in the response so the browser sends the following get/put request
        return frappe.response

    additional_fonts = [dict(value='simkai',filename='/home/frappe/fonts/simkai.ttf')]
    # add additional fonts here if additional fonts are used in ReportBro Designer

    if frappe.request.method == "PUT":
        # all data needed for report preview is sent in the initial PUT request, it contains
        # the format (pdf or xlsx), the report itself (report_definition), the data (test data
        # defined within parameters in the Designer) and is_test_data flag (always True
        # when request is sent from Designer)
        json_data = frappe.request.get_json(silent=True)        
        if json_data is None:
            return None
        output_format = json_data.get("outputFormat")
        if output_format not in ("pdf", "xlsx"):
            return None
        report_definition = json_data.get("report")
        doc = frappe.get_doc("Sales Order", "SAL-ORD-2024-00006")
        doc.name = "SAL-ORD-2024-00006"
        data = doc.as_dict()
        is_test_data = False
        #data = json_data.get("data")
        #is_test_data = bool(json_data.get("isTestData"))
        report = None
        report = Report(
                report_definition, data, is_test_data, additional_fonts=additional_fonts
            )
        report_file = report.generate_pdf(add_watermark=False)
        print(type(report_file))
        data_bytes = bytes(report_file)
        frappe.cache().set("999", data_bytes, ex=120)        
        response = Response("key:999")
        response.status_code = 200
        return response
    elif frappe.request.method == 'GET':
        now = datetime.datetime.now()
        output_format = frappe.request.args.get('outputFormat')
        assert output_format in ('pdf', 'xlsx')
        key = frappe.request.args.get('key')
        report = None
        report_file = frappe.cache().get("999")
        response = Response()
        response.headers['Content-Type'] = 'application/pdf'
        response.headers['Content-Disposition'] = 'inline; filename="{filename}"'.format(
                    filename='report-' + str(now) + '.pdf')        
        response.status_code = 200
        response.set_data(report_file)
        return response
    else:
         return


def jsonconverter(val):
    """Handles json encoding of datetime and Decimal"""
    if isinstance(val, datetime.datetime):
        return "{date.year}-{date.month}-{date.day}".format(date=val)
    if isinstance(val, decimal.Decimal):
        return str(val)
